package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.MyPageResult;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.entity.Article;
import com.itheima.ydd.entity.YddUser;
import com.itheima.ydd.service.ArticleService;
import com.itheima.ydd.service.YddUserService;
import com.itheima.ydd.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * [前台登录]
 *
 * @author : [Cr Mr]
 * @version : [v1.0]
 * @date : [2022/3/3 9:53]
 */
@Slf4j
@RestController
@RequestMapping("")
public class LoginController {
    @Autowired
    private YddUserService yddUserService;

    @Autowired
    private ArticleService articleService;


    /***
     * Desc:  登录
     * @param yddUser
     * @return {@link ResultData}
     * @author Cr Mr
     * @date 2022/3/3 9:30
     */

    @PostMapping("home/index/login")
    public ResultData login(HttpSession httpSession, @RequestBody YddUser yddUser) {
        log.info("登录YddUser：{}", yddUser);
        //1.将页面提交的密码password进行md5加密处理
        String password = DigestUtils.md5Hex(yddUser.getPassword().getBytes());

        //2.根据页面提交的Mobile查询数据库
        LambdaQueryWrapper<YddUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(YddUser::getMobile, yddUser.getMobile());
        YddUser yddUser1 = yddUserService.getOne(queryWrapper);
        //3.如果没有查询到则返回登录失败结果
        if (yddUser1 == null) {
            return ResultData.error("登录失败");
        }
        //4.密码比对，如果不一致则返回登录失败结果
        if (!yddUser1.getPassword().equals(password)) {
            return ResultData.error("登录失败");
        }
        //6.登录成功，则将用户的id传入session并返回登录成功结果
        httpSession.setAttribute("yddUser", yddUser1.getId());

        Map retMap = new HashMap();
        Map tokenMap = new HashMap<>();

        tokenMap.put("id", yddUser1.getId());
        String token = JwtUtils.getToken(tokenMap);
        retMap.put("token", token);

        return ResultData.ok("登录成功", retMap);

    }

    @GetMapping("/user/getUserInfo")
    public ResultData login(HttpSession httpSession) {
        String id = (String) httpSession.getAttribute("yddUser");
        if ("".equals(id)) {
            return ResultData.error("未登录");
        }
        YddUser yddUser = yddUserService.getOne(new LambdaQueryWrapper<YddUser>().eq(YddUser::getId, id));
        yddUser.setPassword("");
        Integer articleNum = articleService.count(new LambdaQueryWrapper<Article>().eq(Article::getUser_id, id));
        HashMap<String, Object> map = new HashMap<>();

        map.put("articleNum", articleNum);
        map.put("collectNum", 0);
        map.put("zanNum", 2);
        map.put("userInfo", yddUser);
        return ResultData.ok("登录成功", map);
    }

    /**
     * Description:
     * date: 2022/3/3 14:29
     *
     * @author: chp
     * @since JDK 1.8
     */

    @GetMapping("/user/userDataList")
    public ResultData userDataList(Integer type, Integer page, Integer limit, HttpSession httpSession) {

        String userId = (String) httpSession.getAttribute("yddUser");
        Page<YddUser> userPage = new Page<>(page, limit);

        MyPageResult init = yddUserService.userDataList(type, Integer.parseInt(userId), userPage);
        HashMap<String, MyPageResult> resultHashMap = new HashMap<>();
        resultHashMap.put("list", init);

        return ResultData.ok("", resultHashMap);

    }

    /**
     * Description:前台相关
     * date: 2022/3/3 8:59
     *
     * @author: chp
     * @since JDK 1.8
     */
    @GetMapping("/user/myArticle")
    public ResultData myArticle(@RequestParam Map<String, String> map, HttpSession session) {
        String userId = (String) session.getAttribute("yddUser");
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(userId != null && !"".equals(userId), Article::getUser_id, userId);
        String page = map.get("page");
        String limit = map.get("limit");
        Page<Article> userPage = new Page<>(Integer.parseInt(page), Integer.parseInt(limit));
        Page<Article> yddUserPage = articleService.page(userPage, queryWrapper);
        MyPageResult init = MyPageResult.init(yddUserPage.getTotal(), yddUserPage.getSize(), yddUserPage.getCurrent(), yddUserPage.getRecords());
        return ResultData.ok("", init);

    }


    @PostMapping("/user/editArticle")
    public ResultData editArticle(@RequestBody Map<String, String> map) {
        String author = map.get("author");
        String cateid = map.get("cateid");
        String tags = map.get("tags");
        String pic = map.get("pic");
        String content = map.get("content");
        String status = map.get("status");
        String id = map.get("id");
        Article article = new Article();
        article.setAuthor(author);
        article.setCateid(cateid);
        article.setTags(tags);
        article.setPic(pic);
        article.setContent(content);
        article.setStatus(status);
        article.setId(Integer.parseInt(id));
        articleService.updateById(article);
        return ResultData.ok("", "");

    }

    /**
     * Description:
     * date: 2022/3/3 10:49
     *
     * @author: chp
     * @since JDK 1.8
     */
    @GetMapping("/user/delArticle")
    public ResultData delArticle(@RequestParam String id) {
        articleService.removeById(Integer.parseInt(id));
        return ResultData.ok("", "");
    }

    @PostMapping("/user/addArticle")
    public ResultData addArticle(@RequestBody Map<String, String> map, HttpSession httpSession) {
        String title = map.get("title");
        String author = map.get("author");
        String cateid = map.get("cateid");
        String tags = map.get("tags");
        String pic = map.get("pic");
        String content = map.get("content");
        String status = map.get("status");
        String userId = (String) httpSession.getAttribute("yddUser");
        Article article = new Article();
        article.setTitle(title);
        article.setAuthor(author);
        article.setCateid(cateid);
        article.setTags(tags);
        article.setPic(pic);
        article.setContent(content);
        article.setStatus(status);
        article.setUser_id(userId);
        article.setDefault_data("1");
        articleService.save(article);
        return ResultData.ok("", "");

    }

    /**
     * Description:点赞/取消点赞和收藏/取消收藏
     * date: 2022/3/3 11:06
     *
     * @author: chp
     * @since JDK 1.8
     */
    @GetMapping("/user/userDataHandle")
    public ResultData userDataHandle(@RequestParam Map<String, String> map, HttpSession httpSession) {
        String userId = (String) httpSession.getAttribute("yddUser");


        String type = map.get("type");
        String action = map.get("action");
        String article_id = map.get("article_id");
        if (action.equals("add")) {
            yddUserService.addUserDataHandle(Integer.parseInt(type), Integer.parseInt(article_id), Integer.parseInt(userId));
            return ResultData.ok("", "");

        }

        yddUserService.delUserDataHandle(Integer.parseInt(type), Integer.parseInt(article_id), Integer.parseInt(userId));
        return ResultData.ok("", "");


    }

}
